#include "mserial.h"
#include <QDebug>

MSerial::MSerial()
    :serialtimer(new QTimer(this))
//    : serialPort(new QSerialPort(this))
{
    /* 帧接收超时槽函数绑定 */
    connect(serialtimer, &QTimer::timeout, this, &MSerial::rcvtimeout);
    rcvtimeout_flag = false;

}

MSerial::~MSerial()
{
    closePort();  // 确保关闭串口
}

QStringList MSerial::availablePorts() const
{
    QStringList ports;
    for (const QSerialPortInfo &info : QSerialPortInfo::availablePorts()) {
        ports << info.portName();
    }
    return ports;
}

bool MSerial::openPort(const QString &portName, int baudRate)
{
    /*串口初始化*/
    this->setPortName(portName);
    this->setBaudRate(baudRate);
    if (this->open(QIODevice::ReadWrite)) {
        qDebug() << "Opened port:" << portName;
        return true;
    } else {
        qDebug() << "open faile" << Qt::endl;
        return false;
    }
}

void MSerial::closePort()
{
    if (this->isOpen()) {
        this->close();
        qDebug() << "Closed port.";
    }
}

bool MSerial::isPortOpen() const
{
    return this->isOpen();
}

void MSerial::rcvtimeout()
{
    rcvtimeout_flag =true;
}
